﻿using UnityEngine;
using UnityEngine.UI;

public static class AStarRes
{
	public static GameObject wall;
	public static GameObject NodePre;
	public static Material openNodeMat;
	public static Material closeNodeMat;
	private static GameObject[,] NodeGos;

	private static GameObject Walls;
	private static GameObject Nodes;


	public static void Init(int row, int col)
	{
		wall = Resources.Load<GameObject>("Wall");
		NodePre = Resources.Load<GameObject>("Node");
		openNodeMat = Resources.Load<Material>("OpenNode_Mat");
		closeNodeMat = Resources.Load<Material>("CloseNode_Mat");

		Walls = new GameObject("Walls");
		Nodes = new GameObject("Nodes");

		NodeGos = new GameObject[col, row];

		for (int i = 0; i < col; i++) {
			for (int j = 0; j < row; j++) {
				NodeGos[i, j] = null;
			}
		}
	}

	/// <summary>
	/// 画节点
	/// </summary>
	/// <param name="step"></param>
	/// <param name="type"></param>
	/// <param name="node"></param>
	public static void DrawNode(int step, DrawNodeType type, AStarNode node) {
//		return;
		if (NodeGos[node.Index.X, node.Index.Y] == null) {
			NodeGos[node.Index.X, node.Index.Y] = Object.Instantiate(NodePre);
			NodeGos[node.Index.X, node.Index.Y].transform.position = node.Position;
			NodeGos[node.Index.X, node.Index.Y].transform.SetParent(Nodes.transform);
		}
		switch (type) {
			case DrawNodeType.OpenNode:
				NodeGos[node.Index.X, node.Index.Y].GetComponent<MeshRenderer>().sharedMaterial = openNodeMat;
				NodeGos[node.Index.X, node.Index.Y].transform.GetChild(0).GetChild(0).GetComponent<Text>().text = step.ToString();
				break;
			case DrawNodeType.CloseNode:
				MeshRenderer render = NodeGos[node.Index.X, node.Index.Y].GetComponent<MeshRenderer>();
				render.sharedMaterial = closeNodeMat;
				break;
			default:
				break;
		}
	}

	/// <summary>
	/// 画障碍物
	/// </summary>
	/// <param name="node"></param>
	public static void DrawWall(AStarNode node) {
//		return;
		if (node.CanMove)
		{
			if (NodeGos[node.Index.X, node.Index.Y] != null) {
				Object.Destroy(NodeGos[node.Index.X, node.Index.Y]);
			}
		}
		else
		{
			GameObject go = Object.Instantiate(wall, node.Position, Quaternion.identity) as GameObject;
			go.name = "Wall";
			go.transform.SetParent(Nodes.transform);
			if (NodeGos[node.Index.X, node.Index.Y] != null)
			{
				Object.Destroy(NodeGos[node.Index.X, node.Index.Y]);
			}
			NodeGos[node.Index.X, node.Index.Y] = go;
		}
	}
}
